<template style="height: 100%;">
	<view class="page-container">
		<navBar v-if="isShowCustomNavBar" :navbarData.sync="navbarData"></navBar>
		<view class="canvas-img">
			<image mode="aspectFit" v-if="canvasPath" :src="canvasPath" lazy-load="true"></image>
			<canvas id="canvasShareImg" class="cas" type="2d"
				:style="{ width: canvasW + 'px', height: canvasH + 'px', top: '2220rpx'}"></canvas>
		</view>
		<view class="footer-new" :class="[isIpx ? 'fix-iphonex-button' : '']">
			<button open-type="share">微信分享</button>
			<button class="save-img" @click='downImg' v-if="writePhotosAlbum">保存图片</button>
			<button class="save-img" @click='handleSetting' v-else>保存图片</button>
		</view>
		<!-- 弱提示 弹窗 -->
		<toast-popup ref="toastPopup" @onToastPopupClick="onToastPopupClick"></toast-popup>
	</view>
</template>

<script>
	import NavBar from '../../components/common/navbar';
	import api from '@/api/api';
	import {
		CUSTOMER_INFO
	} from '@/utils/constant';
	import {
		changeToObj
	} from '@/utils/commonActItems.js'
	export default {
		components: {
			navBar: NavBar,
		},
		data() {
			return {
				isShowCustomNavBar: true,
				postImage: '',
				navbarData: {
					showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
					navbarTitle: '' //导航栏 中间的标题
				},
				isIpx: false,
				canvasPath: '',
				canvasW: 310,
				canvasH: 550,
				memberCode: '',
				writePhotosAlbum: true,
        sharePosterPath: 'pages/customer/wishListShare', // 'pages/customer/wishListShare'
        shareId: "",
        mainImg: "",
        pageCode: "wishListShareImg",
        shareImage: '',   //页面分享图片
        shareTitle: '',   //页面分享标题
        pagePath: '',     //页面分享路径
        pageQuery: '',    //页面分享参数
			}
		},
		async onLoad(options) {
      //  获取配置分享背景图
      this.mainImg = await this.handleGetShareImg();
      //  查询配置的分享数据
      this.getPageShareData();
      if(options && options.shareid && this.mainImg){
        wx.showLoading({
        	title: '海报生成中...',
        })
        this.shareId = options.shareid;
        this.sharePosterPath =`pages/customer/wishListShare?id=${options.shareid}`;
        this.createPosterSunCode();
        wx.getSetting({
        	complete: res => {
        		if (res.authSetting['scope.writePhotosAlbum'] === false) {
        			this.writePhotosAlbum = false
        		}
        	}
        })
      }
		},
		onShow() {
			let systemInfo = uni.getSystemInfoSync();
			this.isIpx = systemInfo.model.indexOf('iPhone X') !== -1 || systemInfo.model.indexOf('iPhone1') !== -1 ||
				systemInfo.model.indexOf('unknown<iPhone13') !== -1;
		},
		methods: {
			/**
			 * 展示弱提示
			 * @param {Object} msg 文案
			 */
			handleShowTextToast(msg){
				try{
					this.$refs.toastPopup.showToast(msg);
				}catch(e){}
			},
			/**
			 * 若提示按钮点击回调
			 * @param {Object} data.type 类型：confirm确定，cancel取消
			 * @param {Object} data.callBackData 呼气弹窗时传入的数据
			 */
			onToastPopupClick(data){},
      /**
       * 查询分享朋友圈数据
       * @param {Object} option
       */
      async getPageShareData() {
        try {
          const res = await this.$commonFunction.getShareinfoByCode(this.pageCode);
          this.shareImage = res.shareImage;
          this.shareTitle = res.shareTitle;
          this.pagePath = res.pagePath; //  当前页面路由
          this.pageQuery = res.pageQuery; //  当前页面url参数
        } catch (e) {}
      },
      // 获取配置分享背景图
      async handleGetShareImg(){
        try{
          const resData = await api.getUtoolsJson({
            type: this.pageCode
          });
          if (resData.success && resData.data) {
            const uData = JSON.parse(resData.data);
            const _imgs = await this.filterUtoolsShopLists(uData,'type','img');
            if(_imgs && _imgs.src) return _imgs.src;
          }
          return "";
        }catch(e){
          return "";
        }
      },
      //  筛选utools json中的商品列表对象
      async filterUtoolsShopLists(data,key,value){
        try{
          if(data && data[key] && data[key] === value) return data;
          if(data && data.children && data.children.length){
            for(let i=0;i<data.children.length;i++){
              const res = this.filterUtoolsShopLists(data.children[i], key,value);
              if(res) return res;
            }
          }
          return null;
        }catch(e){
          return null;
        }
      },
			handleSetting() {
				wx.showModal({
					title: '提示',
					content: '需要您授权保存相册',
					showCancel: false,
					success: modalSuccess => {
						wx.openSetting({
							success: res => {
								if (res.authSetting['scope.writePhotosAlbum']) {
									wx.showModal({
										title: '提示',
										content: '获取权限成功，再次点击下载海报',
										showCancel: false
									})
									this.writePhotosAlbum = true
								} else {
									wx.showModal({
										title: '提示',
										content: '获取权限失败，将无法保存到相册',
										showCancel: false,
									})
								}
							},
						})
					}
				})
			},
			async showPoster(sunCodeUrl) {
				const _that = this;
        const _arr = sunCodeUrl ? [this.mainImg, sunCodeUrl] : [this.mainImg];
        const getImages = _arr.map((imgSrc) => {
        	return new Promise(async (resolve) => {
        		const r = await this.getImageInfo({
        			imgSrc
        		})
        		resolve(r)
        	})
        })
        const [mainPic, sunCodeImage] = await Promise.all(getImages);
				const { ctx, canvas } = await this.getCtx();
        //  绘制背景
				const main = await this.imgeOnload(mainPic.path, canvas);
				ctx.drawImage(main, 0, 0, this.canvasW, this.canvasH);
        if(sunCodeImage && sunCodeImage.path){
          //  绘制太阳码
          const sunCode = await this.imgeOnload(sunCodeImage.path, canvas);
          ctx.drawImage(sunCode, 223, 450, 64, 64);
        }

				uni.canvasToTempFilePath({
					canvas: canvas,
					success(res) {
						_that.canvasPath = res.tempFilePath;
						wx.hideLoading();
					}
				})
				return
			},
			imgeOnload(src, canvas) {
				return new Promise((resolve, reject) => {
					let img = canvas.createImage();
					img.src = src
					img.onload = (e) => {
						resolve(img);
					};
					img.onerror = (e) => {
						resolve("绘制失败-图片加载失败");
					}
				});
			},
			getCtx() {
				return new Promise(async (resolve) => {
					uni.createSelectorQuery()
						.select('#canvasShareImg') // 在 WXML 中填入的 id
						.fields({
							node: true,
							size: true
						})
						.exec((res) => {
							// Canvas 对象
							const canvas = res[0].node;
							// Canvas 绘制上下文
							const ctx = canvas.getContext('2d');
							// 初始化画布大小
							const dpr = wx.getWindowInfo().pixelRatio;
							canvas.width = this.canvasW * dpr;
							canvas.height = this.canvasH * dpr;
							ctx.scale(dpr, dpr);
							resolve({ ctx, canvas });
						})
				})
			},
			//二维码或太阳
			async getImageInfo({imgSrc}) {
				let _this = this;
				return new Promise((resolve, errs) => {
					uni.getImageInfo({
						src: imgSrc,
						success: function(image) {
							resolve(image);
						},
						fail(err) {
							errs(err);
							wx.hideLoading();
							_this.handleShowTextToast('海报生成失败');
						}
					}, this);
				});
			},
			// 动态生成太阳码
			async createPosterSunCode() {
				const that = this;
				let scene = await this.setScence()
				let sharePosterPath = this.sharePosterPath;
				let page;
				if (sharePosterPath?.indexOf('?') > 0) {
					page = sharePosterPath.substring(0, sharePosterPath.indexOf('?'))
				} else {
					page = sharePosterPath
				}
				let merchantInfo = uni.getStorageSync('merchantInfo');
				let customerInfo = uni.getStorageSync('customerInfo');
				const result = await api.createSunCode({
					header: {
						jwt: customerInfo.jwt
					},
					method: 'POST',
					query: {
						appId: uni.getAccountInfoSync().miniProgram.appId,
						scene: scene,
						page: page,
						envVersion: api.environment == 'trial' ? 'trial' : 'release',
						outputType: 'file-url'
					}
				});
        const sunCode = (result.code == 1000 && result.data) ? result.data : "";
        this.showPoster(sunCode)
			},
			// 设置自定义海报参数
			async setScence() {
				let customerInfo = uni.getStorageSync(CUSTOMER_INFO) || '';
				let query, values;
				let sharePosterPath = this.sharePosterPath;
				if (sharePosterPath?.indexOf('?') > 0) {
					query = sharePosterPath.substring(sharePosterPath?.indexOf('?') + 1,
						sharePosterPath.length)
					values = changeToObj(query)
				}
				const sence = await api.setScence({
					method: 'POST',
					query: {
						key: `sunCode_wishList_${this.shareId}`,
						value: JSON.stringify(values)
					},
				})
				if (sence.code === 1000) {
					return sence.data.key
				}
			},
      //保存海报图分享
			downImg() {
				const that = this;
				wx.saveImageToPhotosAlbum({
					filePath: this.canvasPath,
					success: result => {
						that.handleShowTextToast('海报已保存，快去分享给好友吧。');
					},
					fail: err => {
						wx.hideLoading();
					},
				});
			},
			onShareAppMessage(res) {
				this.$sr.setContext({ share_title: this.shareTitle || 'THE MACALLAN EBOUTIQUE麦卡伦' });
        let path = this.sharePosterPath || "pages/home/home";
        this.$commonSensors.sensorsPageShare();
        return this.$commonFunction.commonShare(res, this.shareTitle, path, this.shareImage);
			},
		}
	}
</script>

<style lang="scss">
	.canvas-img {
		position: relative;
		margin: auto;
		display: flex;
		justify-content: center;

		&.fix-iphonex-button {
			margin: 100rpx auto 0;
		}

		.cas {
			background: #fff;
			position: fixed;
			top: -2000rpx;
		}

		image {
			width: 620rpx;
			height: 1100rpx;
		}
	}

	.footer-new {
		position: fixed;
		display: flex;
		flex-direction: row;
		justify-content: space-around;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 32rpx 48rpx 64rpx;
		align-items: center;
		z-index: 9999;
		background-color: #fff;

		button {
			margin: 0;
			width: 320rpx;
			height: 80rpx;
			display: block;
			line-height: 72rpx;
			font-size: 28rpx;
			box-sizing: border-box;
			border: 2px solid #000000;
			color: #000000 !important;
			background-color: #fff !important;
			padding: 0 !important;
			border-radius: 48rpx 16rpx 48rpx 48rpx;
      font-family: NotoSansSC-Medium;
		}
	}

	.page-container {
		display: flex;
		justify-content: center;
		background: #ECECEC;
		align-items: center;
		height: 100vh;
	}
</style>
